//
//  CoreDataManager.m
//  gweAD
//
//  Created by Marx on 2016/10/31.
//  Copyright © 2016年 mengy. All rights reserved.
//

#import "CoreDataManager.h"

@implementation CoreDataManager

+ (CoreDataManager *)sharedCoreDataManager
{
    static CoreDataManager *sharedCoreDataManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedCoreDataManager = [[self alloc] init];
    });
    return sharedCoreDataManager;
}

- (CoreDataOperationResult)insertCoreDataWithEntityName:(NSString *)entityName andDataDic:(NSDictionary *)dataDic
{
    AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    
    NSManagedObjectContext *managedObjectContext = delegate.managedObjectContext;
    NSManagedObject *managedObject = [NSEntityDescription insertNewObjectForEntityForName:entityName inManagedObjectContext:managedObjectContext];
    [managedObject setValuesForKeysWithDictionary:dataDic];
    NSError *error;
    if ([managedObjectContext save:&error]) {
        return CoreDataOperationSucceeded;
    }else{
        NSLog(@"%@保存失败：%@",entityName,[error localizedDescription]);
        return CoreDataOperationFailed;
    }
}

- (NSArray *)selectCoreDataWithEntityName:(NSString *)entityName andCriterionDic:(NSDictionary *)criterionDic
{
    AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    NSManagedObjectContext *managedObjectContext = delegate.managedObjectContext;
    NSEntityDescription *entityDescription = [NSEntityDescription entityForName:entityName inManagedObjectContext:managedObjectContext];
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    [fetchRequest setEntity:entityDescription];
    NSMutableArray *criterionArray = [[NSMutableArray alloc] init];
    for (NSString *key in [criterionDic allKeys]) {
        [criterionArray addObject:[NSString stringWithFormat:@"%@ == '%@'",key,criterionDic[key]]];
    }
    NSString *criterionStr;
    for (int i = 0; i<[criterionArray count]; i++) {
        if (i == 0) {
            criterionStr = [NSString stringWithFormat:@"%@",criterionArray[i]];
        }else{
            criterionStr = [NSString stringWithFormat:@"%@ and %@",criterionStr,criterionArray[i]];
        }
    }
    if (criterionStr.length >0) {
        NSPredicate *predicate = [NSPredicate predicateWithFormat:criterionStr];
        [fetchRequest setPredicate:predicate];
    }
    
    NSError *error;
    NSArray *fetchedObjects = [managedObjectContext executeFetchRequest:fetchRequest error:&error];
    if (error) {
        NSLog(@"%@查询失败：%@",entityName,[error localizedDescription]);
    }
    return fetchedObjects;
}

- (NSArray *)selectCoreDataWithEntityName:(NSString *)entityName andCriterionString:(NSString *)criterionString andSortKey:(NSString *)sortKey andAscending:(BOOL)ascending
{
    AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    NSManagedObjectContext *managedObjectContext = delegate.managedObjectContext;
    NSEntityDescription *entityDescription = [NSEntityDescription entityForName:entityName inManagedObjectContext:managedObjectContext];
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    [fetchRequest setEntity:entityDescription];
    if (criterionString.length >0) {
        NSPredicate *predicate = [NSPredicate predicateWithFormat:criterionString];
        [fetchRequest setPredicate:predicate];
    }
    if (sortKey.length > 0) {
        NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:sortKey ascending:ascending];
        [fetchRequest setSortDescriptors:@[sortDescriptor]];
    }
    
    NSError *error;
    NSArray *fetchedObjects = [managedObjectContext executeFetchRequest:fetchRequest error:&error];
    if (error) {
        NSLog(@"%@查询失败：%@",entityName,[error localizedDescription]);
    }
    return fetchedObjects;
}


- (CoreDataOperationResult)deleteCoreDataWithEntityName:(NSString *)entityName andCriterionDic:(NSDictionary *)criterionDic
{
    AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    NSManagedObjectContext *managedObjectContext = delegate.managedObjectContext;
    
    NSArray *fetchedObjects = [self selectCoreDataWithEntityName:entityName andCriterionDic:criterionDic];
    if ([fetchedObjects count] <=0) {
        NSLog(@"%@删除失败：没有符合条件的数据",entityName);
        return CoreDataOperationNoMatching;
    }
    NSError *error;
    for (NSManagedObject *obj in fetchedObjects) {
        [managedObjectContext deleteObject:obj];
    }
    if ([managedObjectContext save:&error]) {
        return CoreDataOperationSucceeded;
    }else{
        NSLog(@"%@删除失败：%@",entityName,[error localizedDescription]);
        return CoreDataOperationFailed;
    }
}

- (CoreDataOperationResult)updateCoreDataWithEntityName:(NSString *)entityName andCriterionDic:(NSDictionary *)criterionDic andNewDataDic:(NSDictionary *)newDataDic
{
    AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    NSManagedObjectContext *managedObjectContext = delegate.managedObjectContext;
    
    NSArray *fetchedObjects = [self selectCoreDataWithEntityName:entityName andCriterionDic:criterionDic];
    if ([fetchedObjects count] <=0) {
        NSLog(@"%@更新失败：没有符合条件的数据",entityName);
        return CoreDataOperationNoMatching;
    }
    NSError *error;
    for (NSManagedObject *obj in fetchedObjects) {
        for (NSString *key in newDataDic) {
            [obj setValue:newDataDic[key] forKey:key];
        }
    }
    if ([managedObjectContext save:&error]) {
        return CoreDataOperationSucceeded;
    }else{
        NSLog(@"%@更新失败：%@",entityName,[error localizedDescription]);
        return CoreDataOperationFailed;
    }
}

@end
